package com.suneast.suneaststore.modules.personal.address;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.suneast.suneaststore.API;
import com.suneast.suneaststore.app.AccountManager;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.bean.personal.address.AreaBean;
import com.suneast.suneaststore.modules.personal.address.event.AddAddressResult;
import com.suneast.suneaststore.modules.personal.address.event.DeletedAddress;
import com.suneast.suneaststore.modules.personal.address.event.GotAddressInfo;
import com.suneast.suneaststore.modules.personal.address.event.GotAddressList;
import com.suneast.suneaststore.modules.personal.address.event.GotAreaList;
import com.suneast.suneaststore.modules.personal.address.event.GotCurAreaList;
import com.suneast.suneaststore.modules.personal.address.event.GotProvinceList;
import com.suneast.suneaststore.modules.personal.address.event.ModifyAddressResult;
import com.suneast.suneaststore.modules.personal.address.event.SetDefaultAddressResult;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.util.log.LatteLogger;
import com.suneast.suneaststore.util.net.RestClient;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class AddressHandler {

    static void setDefaultAddress(int id) {
        RestClient.builder()
                .url(API.SET_DEFAULT_ADDRESS)
                .params("id", id)
                .params("token", AccountManager.getToken())
                .success((response) -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSONObject.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new SetDefaultAddressResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new SetDefaultAddressResult(Flag.Result.FAILURE));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "setIsdefault failure");
                    EventBus.getDefault().post(new SetDefaultAddressResult(Flag.Result.FAILURE));

                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "setIsdefault error code = "
                            + code + " msg = " + msg);
                    EventBus.getDefault().post(new SetDefaultAddressResult(Flag.Result.FAILURE));
                })
                .build()
                .post();
    }

    static void addAddress(AddressBean addressBean) {
        RestClient.builder()
                .url(API.ADD_ADDRESS)
                .params("token", AccountManager.getToken())
                .params("province", addressBean.getProvince())
                .params("city", addressBean.getCity())
                .params("area", addressBean.getArea())
                .params("town", addressBean.getTown())
                .params("pid", addressBean.getPid())
                .params("cid", addressBean.getCid())
                .params("aid", addressBean.getAid())
                .params("tid", addressBean.getTid())
                .params("type", addressBean.getType())
                .params("realname", addressBean.getRealname())
                .params("mobile", addressBean.getMobile())
                .params("address", addressBean.getAddress())
                .params("isdefault", addressBean.getIsdefault())
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new AddAddressResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new AddAddressResult(Flag.Result.FAILURE));
                        LatteLogger.e("test", "requestAddressList msg = "
                                + rootJObj.getString("msg"));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "addAddress failure");

                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "addAddress error code = "
                            + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void modifyAddress(AddressBean addressBean) {
        RestClient.builder()
                .url(API.ADD_ADDRESS)
                .params("token", AccountManager.getToken())
                .params("id", addressBean.getId())
                .params("province", addressBean.getProvince())
                .params("city", addressBean.getCity())
                .params("area", addressBean.getArea())
                .params("town", addressBean.getTown())
                .params("pid", addressBean.getPid())
                .params("cid", addressBean.getCid())
                .params("aid", addressBean.getAid())
                .params("tid", addressBean.getTid())
                .params("type", addressBean.getType())
                .params("realname", addressBean.getRealname())
                .params("mobile", addressBean.getMobile())
                .params("address", addressBean.getAddress())
                .params("isdefault", addressBean.getIsdefault())
                .success(response -> {
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new ModifyAddressResult(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new ModifyAddressResult(Flag.Result.FAILURE));
                        LatteLogger.e("test", "modifyAddress msg = "
                                + rootJObj.getString("msg"));
                    }
                })
                .failure(() -> {
                    EventBus.getDefault().post(new ModifyAddressResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "modifyAddress failure");
                })
                .error((int code, String msg) -> {
                    EventBus.getDefault().post(new ModifyAddressResult(Flag.Result.FAILURE));
                    LatteLogger.e("error", "modifyAddress failure");
                })
                .build()
                .post();
    }

    static void requestAddressList() {
        RestClient.builder()
                .url(API.ADDRESS_LIST)
                .params("token", AccountManager.getToken())
                .params("psize", 20)
                .params("pindex", 1)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        if (dataJObj.getIntValue("total") > 0) {
                            ArrayList<AddressBean> beanList = new ArrayList<>();
                            JSONArray list = dataJObj.getJSONArray("list");
                            for (int i = 0, length = list.size(); i < length; i++) {
                                AddressBean bean = new AddressBean();
                                JSONObject jObj = list.getJSONObject(i);
                                bean.setId(jObj.getIntValue("id"));
                                bean.setProvince(jObj.getString("province"));
                                bean.setCity(jObj.getString("city"));
                                bean.setArea(jObj.getString("area"));
                                bean.setTown(jObj.getString("town"));
                                bean.setIsdefault(jObj.getIntValue("isdefault"));
                                bean.setPid(jObj.getIntValue("pid"));
                                bean.setCid(jObj.getIntValue("cid"));
                                bean.setAid(jObj.getIntValue("aid"));
                                bean.setTid(jObj.getIntValue("tid"));
                                bean.setRealname(jObj.getString("realname"));
                                bean.setMobile(jObj.getString("mobile"));
                                bean.setAddress(jObj.getString("address"));
                                beanList.add(bean);
                            }
                            EventBus.getDefault().post(new GotAddressList(beanList));
                        } else {
                            LatteLogger.e("test", "requestAddressList,but no address");
                        }
                    } else {
                        LatteLogger.e("test", "requestAddressList msg = "
                                + rootJObj.getString("msg"));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestAddressList failure");

                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestAddressList failure");
                })
                .build()
                .post();
    }

    static void deleteAddress(int id) {
        RestClient.builder()
                .url(API.DELETE_ADDRESS)
                .params("id", id)
                .params("token", AccountManager.getToken())
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        EventBus.getDefault().post(new DeletedAddress(Flag.Result.SUCCEED));
                    } else {
                        EventBus.getDefault().post(new DeletedAddress(Flag.Result.FAILURE));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "removeAddress failure");
                    EventBus.getDefault().post(new DeletedAddress(Flag.Result.FAILURE));

                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "removeAddress error code = " + code + " msg = " + msg);
                    EventBus.getDefault().post(new DeletedAddress(Flag.Result.FAILURE));
                })
                .build()
                .post();
    }

    static void requestProvinceList() {
        RestClient.builder()
                .url(API.AREA_LIST)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONArray jsonArray = rootJObj.getJSONArray("data");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            ArrayList<AreaBean> arrayList = parseJArray(jsonArray);
                            EventBus.getDefault().post(new GotProvinceList(arrayList));
                        }
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestAreaList failure");
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestAreaList error code = " + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void requestAreaList(int id) {
        RestClient.builder()
                .url(API.AREA_LIST)
                .params("id", id)
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONArray jsonArray = rootJObj.getJSONArray("data");
                        if (jsonArray != null && jsonArray.size() > 0) {
                            ArrayList<AreaBean> arrayList = parseJArray(jsonArray);
                            EventBus.getDefault().post(new GotAreaList(arrayList));
                        }
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestAreaList failure");
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestAreaList error code = " + code + " msg = " + msg);
                })
                .build()
                .post();

    }

    static void requestAddressInfo(int areaId) {
        RestClient.builder()
                .url(API.POST_ADDRESS)
                .params("id", areaId)
                .params("token", AccountManager.getToken())
                .success(response -> {
                    LatteLogger.json("test", response);
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        JSONObject addressJObj = dataJObj.getJSONArray("address")
                                .getJSONObject(0);
                        AddressBean addressBean = new AddressBean();
                        addressBean.setId(addressJObj.getIntValue("id"));
                        addressBean.setUniacid(addressJObj.getIntValue("uniacid"));
                        addressBean.setOpenid(addressJObj.getString("openid"));
                        addressBean.setRealname(addressJObj.getString("realname"));
                        addressBean.setMobile(addressJObj.getString("mobile"));
                        addressBean.setProvince(addressJObj.getString("province"));
                        addressBean.setCity(addressJObj.getString("city"));
                        addressBean.setArea(addressJObj.getString("area"));
                        addressBean.setTown(addressJObj.getString("town"));
                        addressBean.setAddress(addressJObj.getString("address"));
                        addressBean.setIsdefault(addressJObj.getIntValue("isdefault"));
                        addressBean.setZipcode(addressJObj.getString("zipcode"));
                        addressBean.setDeleted(addressJObj.getIntValue("deleted"));
                        addressBean.setStreet(addressJObj.getString("street"));
                        addressBean.setStreetdatavalue(addressJObj.getString("streetdatavalue"));
                        addressBean.setDatavalue(addressJObj.getIntValue("pid"));
                        addressBean.setType(addressJObj.getIntValue("type"));
                        addressBean.setStorename(addressJObj.getString("storename"));
                        addressBean.setPid(addressJObj.getIntValue("pid"));
                        addressBean.setCid(addressJObj.getIntValue("cid"));
                        addressBean.setAid(addressJObj.getIntValue("aid"));
                        addressBean.setTid(addressJObj.getIntValue("tid"));
                        addressBean.setMerchid(addressJObj.getIntValue("merchid"));

                        EventBus.getDefault().post(new GotAddressInfo(addressBean));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestAddressInfo failure");

                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestAddressInfo error code = " + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    static void requestCurAreaList(int areaId) {
        RestClient.builder()
                .url(API.POST_ADDRESS)
                .params("id", areaId)
                .params("token", AccountManager.getToken())
                .success(response -> {
                    JSONObject rootJObj = JSON.parseObject(response);
                    if (rootJObj.getIntValue("code") == 1) {
                        JSONObject dataJObj = rootJObj.getJSONObject("data");
                        JSONArray provinceJArray = dataJObj.getJSONArray("province");
                        ArrayList<AreaBean> provinceList = parseJArray(provinceJArray);
                        JSONArray cityJArray = dataJObj.getJSONArray("city");
                        ArrayList<AreaBean> cityList = parseJArray(cityJArray);
                        JSONArray areaJArray = dataJObj.getJSONArray("area");
                        ArrayList<AreaBean> areaList = parseJArray(areaJArray);
                        JSONArray townJArray = dataJObj.getJSONArray("town");
                        ArrayList<AreaBean> townList = parseJArray(townJArray);
                        EventBus.getDefault().post(new GotCurAreaList(provinceList,
                                cityList, areaList, townList));
                    }
                })
                .failure(() -> {
                    LatteLogger.e("error", "requestCurAreaList failure");
                })
                .error((int code, String msg) -> {
                    LatteLogger.e("error", "requestCurAreaList error code = " + code + " msg = " + msg);
                })
                .build()
                .post();
    }

    private static ArrayList<AreaBean> parseJArray(JSONArray jArray) {
        ArrayList<AreaBean> areaList = new ArrayList<>();
        if (jArray != null && jArray.size() > 0) {
            for (int i = 0, length = jArray.size(); i < length; i++) {
                AreaBean bean = new AreaBean();
                JSONObject jsonObject = jArray.getJSONObject(i);
                bean.setId(jsonObject.getIntValue("id"));
                bean.setAreaName(jsonObject.getString("areaname"));
                bean.setParentId(jsonObject.getIntValue("parentid"));
                bean.setShortName(jsonObject.getString("shortname"));
                bean.setLng(jsonObject.getString("lng"));
                bean.setLat(jsonObject.getString("lat"));
                bean.setLevel(jsonObject.getIntValue("level"));
                areaList.add(bean);
            }
        }
        return areaList;
    }
}
